package com.ys.controller.api.purchase;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.entity.purchase.TcgPurchaseByOrder;
import com.ys.entity.purchase.TcgPurchaseByOrderSon;
import com.ys.entity.sys.YsCol;
import com.ys.enume.purchase.TcgPurchaseByOrderEnum;
import com.ys.service.purchase.Api1688Service;
import com.ys.service.purchase.TcgPurchaseByOrderService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.CheckUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.ToolUtil;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 采购订单
 */
@Controller
@RequestMapping("/api/inter/tcgPurchaseByOrder")
public class ApiInterTcgPurchaseByOrderController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcgPurchaseByOrderController.class);

    @Autowired
    private CommonApiService<TcgPurchaseByOrder> commonApiService;

    @Autowired
    private TcgPurchaseByOrderService tcgPurchaseByOrderService;

    @Autowired
    private Api1688Service api1688Service;

    @Autowired
    private CheckUtil checkUtil;

    //菜单id
    private Long menuId = MenuId.TCG_PurchaseByOrder;

    //权限字符
    private final String PERMISSIONS_VIEW = "tcgPurchaseByOrder:view";
    private final String PERMISSIONS = "tcgPurchaseByOrder:";


    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcgPurchaseByOrder setSeachSql(TcgPurchaseByOrder cond){

        cond

                //.addField("CASE WHEN A.PlanToOrderNo IS NOT NULL  THEN A.PlanToOrderNo + '/' +  A.PlanToOrderNum + ' ' + A.CreateMonth + '-NO.' + A.MonthNo ELSE '' END  assembleSign ")//组装标识
                .addField("CASE WHEN A.PlanToOrderNo IS NOT NULL  THEN CAST(A.PlanToOrderNo AS varchar(50)) + '/' +  CAST(A.PlanToOrderNum AS varchar(50)) + ' ' + A.CreateMonth + '-NO.' + CAST(A.MonthNo AS varchar(50)) ELSE '' END  assembleSign ")//组装标识
                .addField("A.OrderStatus AS _ys_orderStatus")//采购管理状态

                .addLeftJoin("TS_UserChange B ON B.UserId = A.AuditingUserId AND B.Status = 1")
                .addField("B.UserId + '/' + B.UserName AS _ys_auditingUserName")//审核人

                .addLeftJoin("TCG_PurchaseByOrderSon C ON C.Pid = A.Id ")//采购订单 (子表
                .addField("C.Sku AS sku")//SKU属性
                .addField("C.RealitySku AS realitySku")//实际SKU属性
                .addField("C.SkuId AS skuId")//skuId
                .addField("C.SpecId AS specId")//specId
                .addField("C.RealityPrice AS realityPrice")//子件实际单价
                .addField("C.SubRealityPrice AS subRealityPrice")//子件单价（采购销售）
                .addField("C.RealityCost AS realityCost")//子件总价（采购销售）
                .addField("C.SubCostPrice AS subCostPrice")//子件单价（采购成本）
                .addField("C.CostPriceTotal AS costPriceTotal")//子件总价（采购成本）
                .addField("C.SubCode AS subCode")//子商品编码
                .addField("C.SupplierId AS supplierId")//供应商ID
                .addField("C.SupplierName AS supplierName")//供应商名称
                .addField("C.OrderManageStatus AS _ys_orderManageStatus")//订单管理状态

                .addLeftJoin("THR_OperateCompanyApply E ON E.Vgsbm = A.Vgsbm ")//运营公司管理表
                .addField("E.Vgsjc AS vgsjc")//采购公司简称
                .addField("E.Vgsmc AS vgsmc")//采购公司名称

                .addLeftJoin("TCG_PurchaseAddress F ON F.Id = A.PurchaseAddressId ")//采购地址维护
                .addField("F.VGjH + ',' + F.VSfH + ',' + F.VDsH + ',' + F.VCqH + ',' + F.VDzH  AS addressDetail")//采购地址

                .addLeftJoin("TP_ProductBasis G ON G.Code = A.SpBm ")//商品母件信息表
                .addField("G.Name AS spName")//商品名称

                .addLeftJoin("TCG_PurchaseByPlan H ON H.Bid = A.PlanBid")//采购计划表
                .addField("H.EffectStock AS effectStockByPlan")//计划审核状态
                .addField("H.Remark AS remarkByPlan")//整单备注
                .addField("FORMAT(H.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS createTimeByPlan")//计划创建时间

                .addLeftJoin("TCG_PurchasePlanGoods I ON I.Id = A.PurchasePlanGoodsId")//采购计划母件表
                .addField("I.StockAmount AS stockAmount")//库存数量
                .addField("I.SpAmount AS spAmount")//采购数量

                .addLeftJoin("TCG_PurchaseByPlanSon J ON J.Id = C.PurchasePlanSonId ")//计划单子件信息表
                .addField("J.SubName AS subName")//子件商品名称
                .addField("J.SubAmount AS subAmount")//子件BOM数量
                .addField("J.Bprice AS bprice")//子件BOM单价、预估单价
                .addField("J.SubRemark AS subRemark")//子件BOM备注
                .addField("J.SubStockAmount AS subStockAmount")//子件库存数量
                .addField("J.PurchaseAmount AS purchaseAmount")//子件采购数量=母件采购数量*子件数量
                .addField("J.JgSl AS jgSl")//子件加购数量
                .addField("J.SubTotalAmount AS subTotalAmount")//子件采购总数
                .addField("J.SubTotalPrice AS subTotalPrice")//子件预估总价

                .addLeftJoin("TS_UserChange K ON K.Id = H.CreateChangeId ")
                .addField("K.UserId + '/' + K.UserName AS _ys_createUserNameByPlan")//计划制单人
                .addField("K.DeptName AS deptNameByPlan")//部门
                .addField("K.RoleName AS roleNameByPlan")//岗位

                .addLeftJoin("YS_ProcInst L ON L.Bid = H.Bid ")
                .addField("FORMAT(L.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTimeByPlan")//审核时间

                .addLeftJoin("TP_ProductBasisComponent M ON M.Code = C.SubCode")//商品子件信息表
                .addField("M.NegotiatedPrice AS negotiatedPrice")//协议价
                .addField("M.LinkIn AS linkIn")//采购链接

        .setOrderby("A.Bid DESC");//排序


        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcgPurchaseByOrder cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            //查询条件
            {
                String orderStatus = ConditionUtil.getConditionValue(conditions, "_ys_orderStatus");//订单状态
                if (orderStatus == null || "".equals(orderStatus)) {
                    //获取查询页面默认显示的状态
                    List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getOrderSearchStatus();
                    //拼接
                    String orders = TcgPurchaseByOrderEnum.OrderStatus.getValueSearchByList(statusList);
                    cond.where("A.OrderStatus IN (" + orders + ")");
                }else {
                    //-1时显示全部状态
                    //非-1时显示选择的对应状态
                    if(!"-1".equals(orderStatus)){
                        cond.where("A.OrderStatus  = "+orderStatus);
                    }
                }

                String _ys_orderManageStatus = ConditionUtil.getConditionValue(conditions, "_ys_orderManageStatus");//订单管理状态
                if(_ys_orderManageStatus!=null && !"".equals(_ys_orderManageStatus)){
                    cond.where("C.OrderManageStatus Like '%" + _ys_orderManageStatus + "%'");
                }

            }


            cond = commonApiService.dataAuth(menuId, cond);
            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }




    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcgPurchaseByOrder cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = commonApiService.dataAuth(menuId, cond);
            cond = setSeachSql(cond);

            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TcgPurchaseByOrder> util = new ExportExcelUtils<>(new TcgPurchaseByOrder());
            String toFilePath = util.exportExcel(listData, listField, "采购订单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }




    //去重
    public List<Map<String, Object>> delSameById(JSONArray subDataArray){
        List<Map<String, Object>> subDataList = new ArrayList<>();
        if(subDataArray!=null && subDataArray.size()>0) {
            for (int i = 0; i < subDataArray.size(); i++) {
                JSONObject jsonObject = subDataArray.getJSONObject(i);
                Map<String, Object> paramsNewByRecord = new HashMap<>();
                for (String key : jsonObject.keySet()) {
                    paramsNewByRecord.put(key, jsonObject.get(key));
                }
                subDataList.add(paramsNewByRecord);
            }
        }
        //去重
        Map<String, List<Map<String, Object>>> groupsByCode = subDataList.stream().collect(Collectors.groupingBy(e->e.get("id").toString()));
        List<Map<String, Object>> resList = new ArrayList<>();
        //遍历，填入去重的信息
        groupsByCode.forEach((k, v) -> resList.add(v.get(0)));

        return resList;
    }


    /**
     * 删除

    @RequiresPermissions(PERMISSIONS+"del")
    @RequestMapping("/del")
    @ResponseBody
    public R del(HttpServletRequest request, String choooseDatas){
        try {
            //获取数据
            List<Map<String, Object>> detailList = delSameById(JSON.parseArray(choooseDatas));
            int doCount = 0;
            String resMsg = "";
            for (int i = 0; i < detailList.size(); i++) {
                Map<String, Object> info = detailList.get(i);
                //处理
                R res = tcgPurchaseOrderService.del(Long.parseLong(info.get("id").toString()));
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg += (info.get("bid")!=null?"单号："+info.get("bid"):"")+"；"+res.getMsg()+"</br>";
                }
            }
            resMsg = "成功删除单"+doCount+"条采购订数据</br>"+resMsg;
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }*/




    /**
     * 审核
     */
    @RequiresPermissions(PERMISSIONS+"examine")
    @RequestMapping("/examine")
    @ResponseBody
    public R examine(HttpServletRequest request, String choooseDatas){
        try {
            //获取数据
            //List<Map<String, Object>> detailList = delSameById(JSON.parseArray(choooseDatas));
            List<Map<String, Object>> detailList = ToolUtil.groupsByJSONArray(
                    JSON.parseArray(choooseDatas),
                    //e->e.get("purchasePlanGoodsId").toString()+"*"+e.get("planBid").toString()+"*"+e.get("operateStatus").toString()
                    e->e.get("bid").toString()
            );
            int doCount = 0;
            String resMsg = "";
            for (int i = 0; i < detailList.size(); i++) {
                Map<String, Object> info = detailList.get(i);
                //Long purchasePlanGoodsId = Long.parseLong(info.get("purchasePlanGoodsId").toString());
                //String planBid = info.get("planBid").toString();
                //int operateStatus = Integer.parseInt(info.get("operateStatus").toString());
                String bid = info.get("bid").toString();
                //处理
                //R res = tcgPurchaseByOrderService.examine(purchasePlanGoodsId,planBid,operateStatus);
                R res = tcgPurchaseByOrderService.examine(bid);
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg += (info.get("bid")!=null?"单号："+info.get("bid"):"")+"；"+res.getMsg()+"</br>";
                }
            }
            resMsg = "成功审核"+doCount+"条采购订单数据</br>"+resMsg;
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 特殊审核
     */
    @RequiresPermissions(PERMISSIONS+"specialExamine")
    @RequestMapping("/specialExamine")
    @ResponseBody
    public R specialExamine(HttpServletRequest request, String choooseDatas){
        try {
            //获取数据
            //List<Map<String, Object>> detailList = delSameById(JSON.parseArray(choooseDatas));

            List<Map<String, Object>> detailList = ToolUtil.groupsByJSONArray(
                    JSON.parseArray(choooseDatas),
                    //e->e.get("purchasePlanGoodsId").toString()+"*"+e.get("planBid").toString()+"*"+e.get("operateStatus").toString()
                    e->e.get("bid").toString()
            );
            int doCount = 0;
            String resMsg = "";
            for (int i = 0; i < detailList.size(); i++) {
                Map<String, Object> info = detailList.get(i);
                //Long purchasePlanGoodsId = Long.parseLong(info.get("purchasePlanGoodsId").toString());
                //String planBid = info.get("planBid").toString();
                //int operateStatus = Integer.parseInt(info.get("operateStatus").toString());
                String bid = info.get("bid").toString();
                //处理
                //R res = tcgPurchaseByOrderService.specialExamine(purchasePlanGoodsId,planBid,operateStatus);
                R res = tcgPurchaseByOrderService.specialExamine(bid);
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg += (info.get("bid")!=null?"单号："+info.get("bid"):"")+"；"+res.getMsg()+"</br>";
                }
            }
            resMsg = "成功审核"+doCount+"条采购订单数据</br>"+resMsg;
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 更换渠道
     */
    @RequiresPermissions(PERMISSIONS+"changeChannel")
    @RequestMapping("/changeChannel")
    @ResponseBody
    public R changeChannel(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            String choooseDatas = params.get("choooseDatas").toString();
            //获取数据
            List<Map<String, Object>> detailList = delSameById(JSON.parseArray(choooseDatas));
            int doCount = 0;
            String resMsg = "";
            for (int i = 0; i < detailList.size(); i++) {
                Map<String, Object> info = detailList.get(i);
                //处理
                R res = tcgPurchaseByOrderService.changeChannel(Long.parseLong(info.get("id").toString()));
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg += (info.get("bid")!=null?"单号："+info.get("bid"):"")+"；"+res.getMsg()+"</br>";
                }
            }
            resMsg = "成功更换"+doCount+"条采购订单的渠道信息</br>"+resMsg;
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 占用红包
     */
    @RequiresPermissions(PERMISSIONS+"occupy")
    @RequestMapping("/occupy")
    @ResponseBody
    public R occupy(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            String choooseDatas = params.get("choooseDatas").toString();
            //获取数据
            List<Map<String, Object>> detailList = delSameById(JSON.parseArray(choooseDatas));
            int doCount = 0;
            String resMsg = "";
            for (int i = 0; i < detailList.size(); i++) {
                Map<String, Object> info = detailList.get(i);
                //处理
                R res = tcgPurchaseByOrderService.occupy(Long.parseLong(info.get("id").toString()));
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg += (info.get("bid")!=null?"单号："+info.get("bid"):"")+"；"+res.getMsg()+"</br>";
                }
            }
            resMsg = "成功操作"+doCount+"条采购订单信息</br>"+resMsg;
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




    /**
     * 刷新订单信息
     */
    @RequiresPermissions(PERMISSIONS+"refreshOrder")
    @RequestMapping("/refreshOrder")
    @ResponseBody
    public R refreshOrder(HttpServletRequest request, String choooseDatas){
        try {
            //获取数据，去重
            List<Map<String, Object>> detailList = delSameById(JSON.parseArray(choooseDatas));
            return tcgPurchaseByOrderService.refreshOrder(detailList);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 创建订单
     */
    @RequiresPermissions(PERMISSIONS+"createOrder")
    @RequestMapping("/createOrder")
    @ResponseBody
    public R createOrder(HttpServletRequest request, String choooseDatas){
        try {
            List<Map<String, Object>> detailList = delSameById(JSON.parseArray(choooseDatas));
            String orderNos = "";
            //获取可以进行创建订单的状态
            List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getCreateOrderStatus();
            for(Map<String, Object> item:detailList){
                String bid = item.get("bid").toString();
                TcgPurchaseByOrder entity = new TcgPurchaseByOrder().setBid(bid).queryFirst();
                if(entity==null || entity.getBid()==null){
                    return R.error("未查询到采购订单信息");
                }
                //验证状态
                boolean statusIsPass = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(statusList,entity.getOrderStatus());
                //验证状态
                if(!statusIsPass){
                    return R.error("只有"+TcgPurchaseByOrderEnum.OrderStatus.getNameStrByList(statusList)+"的订单才可进行创建订单");
                }
                //验证
                List<TcgPurchaseByOrder> tcgPurchaseOrderList = new TcgPurchaseByOrder()
                        .setBid(bid)
                        .where("A.OrderStatus IN ("+TcgPurchaseByOrderEnum.OrderStatus.getValueSearchByList(statusList)+")")
                        .setStatus(1)
                        .queryList();

                //验证是否重复下单
                for(TcgPurchaseByOrder tcgPurchaseOrder:tcgPurchaseOrderList){
                    //验证子件单价
                    List<TcgPurchaseByOrderSon> orderSonList = new TcgPurchaseByOrderSon().setPid(tcgPurchaseOrder.getId()).queryList();
                    for(TcgPurchaseByOrderSon sonInfo : orderSonList){
                        //验证是否重复订单
                        int planSonNum = new TcgPurchaseByOrderSon()
                                .addLeftJoin("TCG_PurchaseByOrder B ON B.Id = A.Pid")
                                .where("B.Status = 1")
                                .setPurchasePlanSonId(sonInfo.getPurchasePlanSonId()).count();
                        if(planSonNum>=2){
                            return R.error(""+"子件"+sonInfo.getSubCode()+"，重复下单，请确认");
                        }
                    }
                }


                if(orderNos.equals("")){
                    orderNos = bid;
                }else {
                    orderNos += ","+bid;
                }
            }
            return api1688Service.create1688Order(orderNos);
            //return api1688Service.get1688OrderDetail(orderNos);

        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 取消订单
     */
    @RequiresPermissions(PERMISSIONS+"cancelOrder")
    @RequestMapping("/cancelOrder")
    @ResponseBody
    public R cancelOrder(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            if(checkUtil.isNullByObject(params.get("cancelReason"))){
                return R.error("请输入取消原因");
            }
            String cancelReason = params.get("cancelReason").toString();
            String choooseDatas = params.get("choooseDatas").toString();
            List<Map<String, Object>> detailList = ToolUtil.groupsByJSONArray(
                    JSON.parseArray(choooseDatas),
                    e->e.get("purchasePlanGoodsId").toString()+"*"+e.get("planBid").toString()+"*"+e.get("operateStatus").toString()+"*"+e.get("orderStatus").toString()
            );
            //String orderNos = "";
            StringBuffer orderNos = new StringBuffer();

            //获取可以进行取消订单的状态
            List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getCancelStatus();

            //获取取消订单时、需要访问1688取消接口的状态
            List<TcgPurchaseByOrderEnum.OrderStatus> sent1688StatusList = TcgPurchaseByOrderEnum.OrderStatus.send1688WhenCancelStatus();

            for(Map<String, Object> item:detailList){
                Long purchasePlanGoodsId = Long.parseLong(item.get("purchasePlanGoodsId").toString());
                String planBid = item.get("planBid").toString();
                int orderStatus = Integer.parseInt(item.get("orderStatus").toString());
                int operateStatus = Integer.parseInt(item.get("operateStatus").toString());
                //TcgPurchaseByOrder entity = new TcgPurchaseByOrder().setId(id).queryFirst();
                List<TcgPurchaseByOrder> entityList = new TcgPurchaseByOrder()
                        .setPlanBid(planBid)
                        .setPurchasePlanGoodsId(purchasePlanGoodsId)
                        .setOrderStatus(orderStatus)
                        .setOperateStatus(operateStatus)
                        //.setStatus(1)
                        //.where("A.OperateStatus IN ("+TcgPurchaseByOrderEnum.OperateStatus.NORMAL.value+","+TcgPurchaseByOrderEnum.OperateStatus.OCCUPY_COUPON.value+")")
                        .queryList();
                if(entityList==null || entityList.size()<=0){
                    return R.error("未查询到采购订单信息");
                }

                for(TcgPurchaseByOrder entity:entityList){
                    //验证状态
                    boolean statusIsPass = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(statusList,entity.getOrderStatus());
                    //验证状态
                    if(!statusIsPass){
                        return R.error("只有"+TcgPurchaseByOrderEnum.OrderStatus.getNameStrByList(statusList)+"的订单才可进行取消订单");
                    }

                    boolean statusIsSend1688 = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(sent1688StatusList,entity.getOrderStatus());
                    if(statusIsSend1688){
                        if(orderNos.length()<=0){
                            orderNos.append(entity.getBid());
                        }else {
                            orderNos.append(",").append(entity.getBid());
                        }
                    }
                }


            }
            if(orderNos.length()>0){
                R res = api1688Service.cancel1688Order(orderNos.toString(),cancelReason,true);
                if(res.getCode().equals(R.Code.SUCCESS.value)){//成功
                    return res;//tcgPurchaseByOrderService.cancelOrder(detailList,cancelReason);
                }else {//失败
                    return res;
                }
            }else {
                return tcgPurchaseByOrderService.cancelOrder(detailList,cancelReason);
            }

        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




    /**
     * 修改商议订单金额（含运）
     */
    @RequiresPermissions(PERMISSIONS+"updateOrderAmountDiscuss")
    @RequestMapping("/updateOrderAmountDiscuss")
    @ResponseBody
    public R updateOrderAmountDiscuss(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            if(params.get("bid")==null || "".equals(params.get("bid").toString())){
                return R.error("单号为空");
            }
            if(params.get("orderAmountDiscuss")==null || "".equals(params.get("orderAmountDiscuss").toString())){
                return R.error("修改商议订单金额为空");
            }
            return tcgPurchaseByOrderService.updateOrderAmountDiscuss(params.get("bid").toString(),params.get("orderAmountDiscuss").toString());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 修改采购订单金额（含税）
     */
    @RequiresPermissions(PERMISSIONS+"updatePurchaseOrderAmount")
    @RequestMapping("/updatePurchaseOrderAmount")
    @ResponseBody
    public R updatePurchaseOrderAmount(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            if(params.get("bid")==null || "".equals(params.get("bid").toString())){
                return R.error("单号为空");
            }
            if(params.get("purchaseOrderAmount")==null || "".equals(params.get("purchaseOrderAmount").toString())){
                return R.error("采购订单金额（含税）为空");
            }
            return tcgPurchaseByOrderService.updatePurchaseOrderAmount(params.get("bid").toString(),params.get("purchaseOrderAmount").toString());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 编辑工作日志
     */
    @RequiresPermissions(PERMISSIONS+"workLog")
    @RequestMapping("/workLog")
    @ResponseBody
    public R workLog(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            if(params.get("workLog")==null || "".equals(params.get("workLog").toString())){
                return R.error("请输入工作日志");
            }
            String choooseDatas = params.get("choooseDatas").toString();
            //获取数据
            List<Map<String, Object>> detailList = delSameById(JSON.parseArray(choooseDatas));
            int doCount = 0;
            String resMsg = "";
            for (int i = 0; i < detailList.size(); i++) {
                Map<String, Object> info = detailList.get(i);
                //处理
                R res = tcgPurchaseByOrderService.workLog(Long.parseLong(info.get("id").toString()),params.get("workLog").toString());
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg += (info.get("bid")!=null?"单号："+info.get("bid"):"")+"；"+res.getMsg()+"</br>";
                }
            }
            resMsg = "成功操作"+doCount+"条采购订单信息</br>"+resMsg;
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 修改协议价
     */
    @RequiresPermissions(PERMISSIONS+"updateNegotiatedPrice")
    @RequestMapping("/updateNegotiatedPrice")
    @ResponseBody
    public R updateNegotiatedPrice(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            if(params.get("bid")==null || "".equals(params.get("bid").toString())){
                return R.error("单号为空");
            }
            if(params.get("negotiatedPrice")==null || "".equals(params.get("negotiatedPrice").toString())){
                return R.error("协议价为空");
            }else {
                boolean isValid = params.get("negotiatedPrice").toString().matches("^[+-]?\\d{1,3}(,\\d{3})*(\\.\\d{1,2})?$|^[+-]?\\d+(\\.\\d{1,3})?$");
                if (!isValid){
                    return R.error("协议价格式错误,只允许最多三位小数点的金额");
                }
            }
            if(params.get("spBm")==null || "".equals(params.get("spBm").toString())){
                return R.error("商品编码为空");
            }
            return tcgPurchaseByOrderService.updateNegotiatedPrice(params.get("bid").toString(),params.get("negotiatedPrice").toString(),params.get("spBm").toString());
        } catch (Exception e) {
            logger.error("修改协议价出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }



}